<?php

namespace app\admin\controller\dts;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\exception\PDOException;
use Exception;
use think\Collection;
/**
 * 学生管理
 *
 * @icon fa fa-circle-o
 */
class Student extends Backend
{

    /**
     * Student模型对象
     * @var \app\admin\model\dts\Student
     */
    protected $model = null;
    protected $userModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\Student;
        $this->view->assign("relationshipList", $this->model->getRelationshipList());

        $this->userModel = new \app\admin\model\User;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $defaultJoin = [
                ['dts_grade grade', 'grade.id = student.grade_id', 'left'],
                ['dts_classes classes', 'classes.id = student.classes_id', 'left'],
            ];

            $list = Db::name('dts_student')->alias('student')
            ->field('student.*,grade.name as grade__name,classes.name as classes__name')
            ->join($defaultJoin)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => paginateList($list));

            return json($result);
        }

        return $this->view->fetch();
    }

    protected function before_add($params)
    {
        $mobile = $params['user']['mobile'];

        $user = \app\admin\model\User::where('mobile', $mobile)->find();
        if(!$user) {
            $salt = Random::alnum();
            $password = $this->auth->getEncryptPassword('123456', $salt);
            $db = \app\admin\model\User::create(['mobile' => $mobile, 'password' => $password, 'salt' => $salt, 'status' => 'normal']);
            $user = $db->getData();
        }

        unset($params['mobile']);

        $params['user_id'] = $user['id'];
        $params['user_mobile'] = $user['mobile'];
        $params['createby'] = $this->auth->nickname;

        return $params;
    }

    protected function row($ids)
    {
        $row = $this->model->with(['user' => function($query) {$query->withField('mobile');}])->where('student.id', $ids)->find();   
        return $row;
    }

    protected function before_edit($params, $changeData, $originData)
    {
        $user = \app\admin\model\User::where('id', $originData['user_id'])->find();
        if($user['mobile'] != $params['user']['mobile']) {
            $num = \app\admin\model\User::where('mobile', $params['user']['user_id'])->count(1);
            if($num) {
                ajaxerror('手机号已存在');
            }
            \app\admin\model\User::where('mobile', $originData['mobile'])->update(['mobile' => $params['user']['mobile']]);
        }
        
        unset($params['mobile']);

        $params['user_id'] = $user['id'];
        $params['user_mobile'] = $user['mobile'];
        $params['createby'] = $this->auth->nickname;
        return $params;
    }

    public function moban() {

        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $path = cdnurl($params['files']);
                //获取文件类型
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                if (!in_array($ext, ['xls', 'xlsx'])) {
                    $this->error(__('Unknown data format'));
                }
                $fileName = 'download/student.xlsx';
                $filePath = ROOT_PATH . 'public' . DS . $fileName;
                try {
                    file_put_contents($fileName, file_get_contents($path));
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

                $database = \think\Config::get('database.database');
                $list = db()->query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", ['fa_dts_student', $database]);
                $fieldArr = [];
                foreach ($list as $k => $v) {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                }

                //加载文件
                $insert = []; $createby = $this->auth->nickname;
                try {
                    $reader = IOFactory::createReader(ucwords($ext));
                    
                    $spreadsheet = $reader->load($filePath);
                    $currentSheet = $spreadsheet->getSheet(0);  //读取文件中的第一个工作表
                    $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                    $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                    $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                    $fields = [];
                    for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                        for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            $fields[] = $val;
                        }
                    }

                    for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                        $values = [];
                        for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                            $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                            $values[] = is_null($val) ? '' : $val;
                        }
                        $row = [];
                        $temp = array_combine($fields, $values);
                        foreach ($temp as $k => $v) {
                            if (isset($fieldArr[$k]) && $k !== '') {
                                $row[$fieldArr[$k]] = $v;
                                $row['createby'] = $createby;
                            }
                        }
                        if ($row) {
                            $insert[] = $row;
                        }
                    }
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

                if (!$insert) {
                    $this->error(__('No rows were updated'));
                }

                Db::startTrans();
                $stuArr = [];
                try {
                    $map1 = new Collection; $map2 = new Collection; $map3 = new Collection;
                    foreach($insert as $item) {

                        if ($map1->offsetExists($item['grade_id'])) {
                            $gradeId = $map1->offsetGet($item['grade_id']);
                        }else {
                            $gradeId = Db::name('dts_grade')->where('name', $item['grade_id'])->value('id');
                            if($gradeId) {
                                $map1[$item['grade_id']] = $gradeId;
                            }
                        }

                        if ($map2->offsetExists($item['classes_id'])) {
                            $classesId = $map2->offsetGet($item['classes_id']);
                        }else {
                            $classesId = Db::name('dts_classes')->where('name', $item['classes_id'])->value('id');
                            if($classesId) {
                                $map2[$item['classes_id']] = $classesId;
                            }
                        }

                        if (!$map3->offsetExists($item['user_mobile'])) {
                            $mobile = $item['user_mobile'];
                            $num = Db::name('user')->where('mobile', $mobile)->count(1);
                            if(!$num) {
                                $map3[$mobile] = $mobile;
                            }
                        }

                        if($gradeId && $classesId) {
                            $item['grade_id'] = $gradeId;
                            $item['classes_id'] = $classesId;
                            $item['gender'] = $item['gender'] == '男' ? 1 : 0;

                            $stuArr[] = $item;
                        }
                        
                    }

                    $userArr = [];
                    foreach($map3->toArray() as $mobile) {
                        $salt = Random::alnum();
                        $password = $this->auth->getEncryptPassword('123456', $salt);
                        $userArr[] = ['mobile' => $mobile, 'password' => $password, 'salt' => $salt, 'status' => 'normal'];
                    }

                    $this->userModel->saveAll($userArr);
                    $this->model->saveAll($stuArr);


                    Db::table('dts_student')->execute('UPDATE fa_dts_student stu INNER JOIN fa_user `user` ON `user`.mobile = stu.user_mobile SET stu.user_id = `user`.id');

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $error = count($insert) - count($stuArr);
                $this->success('成功 '.count($stuArr).' 条，失败 '.$error. ' 条');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
        
    }
}
